import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/auth.config';
import { revalidatePath } from 'next/cache';

export async function PUT(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }

    const destination = await prisma.destination.findUnique({
      where: { 
        id: params.id,
        createdById: session.user.id 
      }
    });

    if (!destination) {
      return NextResponse.json({ error: '目的地不存在或无权限编辑' }, { status: 404 });
    }

    const body = await request.json();

    const updatedDestination = await prisma.destination.update({
      where: { id: params.id },
      data: {
        name: body.name,
        description: body.description,
        imageUrl: body.imageUrl,
        metadata: body.metadata,
      },
    });

    // 重新验证所有相关路径
    revalidatePath('/my-destinations');
    revalidatePath('/destinations');
    revalidatePath(`/destinations/${params.id}`);
    revalidatePath('/profile');  // 如果在个人资料页面也显示目的地

    return NextResponse.json(updatedDestination);
  } catch (error: any) {
    console.error('Update destination error:', error);
    return NextResponse.json(
      { error: '更新目的地失败', details: error.message },
      { status: 500 }
    );
  }
}

export async function DELETE(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }

    const destination = await prisma.destination.findUnique({
      where: { 
        id: params.id,
        createdById: session.user.id 
      },
    });

    if (!destination) {
      return NextResponse.json({ error: '目的地不存在' }, { status: 404 });
    }

    await prisma.destination.delete({
      where: { id: params.id },
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Error deleting destination:', error);
    return NextResponse.json(
      { error: '删除目的地失败' },
      { status: 500 }
    );
  }
} 